import React, { useRef, useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, Space, Tag, Image, Popconfirm, message, Modal, Dropdown, Progress, Badge } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, MoreOutlined, PlayCircleOutlined, ExportOutlined } from '@ant-design/icons';
import { getGameContentList, deleteGameContent, updateGameContentStatus, copyGameContent } from '@/services/learningContentApi';
import GameContentForm from './components/GameContentForm';
import GamePreview from './components/GamePreview';
import moment from 'moment';

const GameContentList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [gameFormVisible, setGameFormVisible] = useState(false);
  const [gamePreviewVisible, setGamePreviewVisible] = useState(false);
  const [currentGame, setCurrentGame] = useState<LEARNING.GameContentModel | undefined>();
  const [editMode, setEditMode] = useState<'create' | 'edit'>('create');

  // 游戏类型标签颜色映射
  const typeColorMap = {
    pronunciation: 'blue',
    listening: 'purple',
    reading: 'cyan',
    writing: 'green',
  };

  // 状态标签颜色映射
  const statusColorMap = {
    active: 'green',
    inactive: 'orange',
    testing: 'blue',
  };

  // 表格列定义
  const columns: ProColumns<LEARNING.GameContentModel>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 60,
      search: false,
    },
    {
      title: '游戏封面',
      dataIndex: 'image_url',
      width: 120,
      search: false,
      render: (_, record) => (
        <Image
          src={record.image_url}
          alt={record.title}
          width={80}
          height={60}
          style={{ objectFit: 'cover', borderRadius: 4 }}
          fallback=""
        />
      ),
    },
    {
      title: '游戏名称',
      dataIndex: 'title',
      width: 200,
      ellipsis: true,
      copyable: true,
    },
    {
      title: '游戏类型',
      dataIndex: 'game_type',
      width: 120,
      valueType: 'select',
      valueEnum: {
        pronunciation: { text: '发音练习', status: 'Processing' },
        listening: { text: '听力训练', status: 'Error' },
        reading: { text: '阅读理解', status: 'Default' },
        writing: { text: '写作练习', status: 'Success' },
      },
      render: (_, record) => {
        const typeMap = {
          pronunciation: '发音练习',
          listening: '听力训练',
          reading: '阅读理解',
          writing: '写作练习',
        };
        return (
          <Tag color={typeColorMap[record.game_type]}>
            {typeMap[record.game_type]}
          </Tag>
        );
      },
    },
    {
      title: '难度等级',
      dataIndex: 'difficulty',
      width: 100,
      valueType: 'select',
      valueEnum: {
        easy: { text: '简单', status: 'Success' },
        medium: { text: '中等', status: 'Warning' },
        hard: { text: '困难', status: 'Error' },
      },
      render: (_, record) => {
        const difficultyMap = { easy: '简单', medium: '中等', hard: '困难' };
        const colorMap = { easy: 'green', medium: 'orange', hard: 'red' };
        return (
          <Tag color={colorMap[record.difficulty]}>
            {difficultyMap[record.difficulty]}
          </Tag>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      valueType: 'select',
      valueEnum: {
        active: { text: '启用', status: 'Success' },
        inactive: { text: '禁用', status: 'Warning' },
        testing: { text: '测试中', status: 'Processing' },
      },
      render: (_, record) => {
        const statusMap = { active: '启用', inactive: '禁用', testing: '测试中' };
        return (
          <Tag color={statusColorMap[record.status]}>
            {statusMap[record.status]}
          </Tag>
        );
      },
    },
    {
      title: '游戏次数',
      dataIndex: 'play_count',
      width: 100,
      search: false,
      render: (count) => (
        <Badge count={count || 0} showZero color="#52c41a" />
      ),
    },
    {
      title: '平均分数',
      dataIndex: 'average_score',
      width: 100,
      search: false,
      render: (score) => score ? `${score.toFixed(1)}分` : '-',
    },
    {
      title: '完成率',
      dataIndex: 'completion_rate',
      width: 120,
      search: false,
      render: (rate) => (
        <Progress
          percent={Math.round((rate || 0) * 100)}
          size="small"
          status={rate > 0.8 ? 'success' : rate > 0.5 ? 'normal' : 'exception'}
        />
      ),
    },
    {
      title: '预计时长',
      dataIndex: 'estimated_duration',
      width: 100,
      search: false,
      render: (duration) => duration ? `${duration}分钟` : '-',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 160,
      search: false,
      valueType: 'dateTime',
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 150,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="preview"
          type="link"
          size="small"
          onClick={() => handlePreview(record)}
        >
          预览
        </Button>,
        <Dropdown
          key="more"
          menu={{
            items: [
              {
                key: 'edit',
                label: '编辑',
                icon: <EditOutlined />,
                onClick: () => handleEdit(record),
              },
              {
                key: 'copy',
                label: '复制',
                onClick: () => handleCopy(record),
              },
              {
                key: 'status',
                label: getStatusAction(record.status),
                onClick: () => handleStatusChange(record),
              },
              {
                type: 'divider',
              },
              {
                key: 'delete',
                label: '删除',
                icon: <DeleteOutlined />,
                danger: true,
                onClick: () => handleDelete(record),
              },
            ],
          }}
        >
          <Button type="link" size="small">
            <MoreOutlined />
          </Button>
        </Dropdown>,
      ],
    },
  ];

  // 获取状态操作文本
  const getStatusAction = (status: string) => {
    switch (status) {
      case 'active':
        return '禁用';
      case 'inactive':
        return '启用';
      case 'testing':
        return '发布';
      default:
        return '更新状态';
    }
  };

  // 处理预览
  const handlePreview = (record: LEARNING.GameContentModel) => {
    setCurrentGame(record);
    setGamePreviewVisible(true);
  };

  // 处理编辑
  const handleEdit = (record: LEARNING.GameContentModel) => {
    setCurrentGame(record);
    setEditMode('edit');
    setGameFormVisible(true);
  };

  // 处理复制
  const handleCopy = async (record: LEARNING.GameContentModel) => {
    try {
      await copyGameContent(record.id, `${record.title} - 副本`);
      message.success('游戏复制成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('游戏复制失败');
    }
  };

  // 处理状态变更
  const handleStatusChange = (record: LEARNING.GameContentModel) => {
    let newStatus: string;
    let actionText: string;
    
    switch (record.status) {
      case 'active':
        newStatus = 'inactive';
        actionText = '禁用';
        break;
      case 'inactive':
        newStatus = 'active';
        actionText = '启用';
        break;
      case 'testing':
        newStatus = 'active';
        actionText = '发布';
        break;
      default:
        return;
    }
    
    Modal.confirm({
      title: `确认${actionText}`,
      content: `确定要${actionText}游戏 "${record.title}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await updateGameContentStatus(record.id, newStatus);
          message.success(`游戏${actionText}成功`);
          actionRef.current?.reload();
        } catch (error) {
          message.error(`游戏${actionText}失败`);
        }
      },
    });
  };

  // 处理删除
  const handleDelete = (record: LEARNING.GameContentModel) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除游戏 "${record.title}" 吗？此操作不可恢复。`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          await deleteGameContent(record.id);
          message.success('删除成功');
          actionRef.current?.reload();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理新建
  const handleCreate = () => {
    setCurrentGame(undefined);
    setEditMode('create');
    setGameFormVisible(true);
  };

  return (
    <PageContainer>
      <ProTable<LEARNING.GameContentModel>
        headerTitle="游戏内容列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleCreate}
          >
            新建游戏
          </Button>,
        ]}
        request={async (params, sort) => {
          const response = await getGameContentList({
            page: params.current,
            limit: params.pageSize,
            title: params.title,
            type: params.type,
            difficulty: params.difficulty,
            status: params.status,
          });
          return {
            data: response.data.list,
            success: response.code === 200,
            total: response.data.pagination.total,
          };
        }}
        columns={columns}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys) => setSelectedRowKeys(keys as number[]),
        }}
        scroll={{ x: 1600 }}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      {/* 游戏表单弹窗 */}
      <GameContentForm
        visible={gameFormVisible}
        mode={editMode}
        initialValues={currentGame}
        onCancel={() => setGameFormVisible(false)}
        onSuccess={() => {
          setGameFormVisible(false);
          actionRef.current?.reload();
        }}
      />

      {/* 游戏预览弹窗 */}
      <GamePreview
        visible={gamePreviewVisible}
        game={currentGame}
        onCancel={() => setGamePreviewVisible(false)}
      />
    </PageContainer>
  );
};

export default GameContentList;
